<template>
  <!--定位考勤新-->
  <div class="containerform2">
    <!--<div class="topPosition flex3" style="height: 40px">-->
      <!--<van-icon name="arrow-left" size="24px" @click="goBack"/>-->
      <!--<div style="width: 24px;"></div>-->
    <!--</div>-->
    <div class="tableBoxHeight">
      <div class="contbox">
        <div class="cardd2" style="min-height: auto; text-align: left;padding: 2rem 1rem;">
          <div class="flex2">
            <div style="width: 30px;text-align: center;">
              <van-icon name="location-o" color="#fff" size="24px"/>
            </div>
            <div style="flex: 1">
              <!--<p style="margin: 0;font-size: 1.6rem;color: #fff">实际定位：{{address}}</p>-->
              <p style="margin: 0;font-size: 1.6rem;color: #fff">{{address2}}</p>
              <p style="margin: 10px 0;font-size: 1.2rem;color: #fff" id="bjTime">{{nowtime}}</p>
              <div class="littletip">
                <p style="color: #333" v-if="loadingPoint == 1">正在获取您的位置...</p>
                <p style="color: green" v-else-if="loadingPoint == 2">当前位置在打卡范围</p>
                <p style="color: #d20707" v-else-if="loadingPoint == 3">不在打卡范围内</p>
                <p style="color: #d20707" v-else-if="loadingPoint == 4">获取位置失败，请尝试重新定位</p>
                <p style="color: #d20707" v-else-if="loadingPoint == 5">验证签名失败</p>
                <p style="color: #d20707" v-else-if="loadingPoint == 6">获取签名失败</p>
                <p style="color: #d20707" v-else-if="loadingPoint == 7">获取考勤点失败，请刷新重试</p>
                <p style="color: #d20707" v-else-if="loadingPoint == 8">获取用户信息失败，请检查微信配置信息</p>
                <p style="color: #d20707" v-else-if="loadingPoint == 9">未获取到考勤点，如有需要，请通过您所在部门申请开通，谢谢</p>

              </div>
            </div>

            <div style="width: 30px;text-align: center;">
              <!--<van-icon name="replay" color="#fff" size="24px" @click="Refresh"/>-->
              <van-icon name="replay" color="#fff" size="24px" @click="Refresh2" v-if="RefreshNum == 1"/>
              <van-icon name="replay" color="#fff" size="24px" v-else  style="opacity: .5"/>
              <!--<van-icon name="replay" color="#fff" size="24px" @click="Refresh3"/>-->
            </div>

          </div>
        </div>

        <!--菜单按钮-->
        <!--<div style="padding: 16px;font-size: 14px" class="flex3">-->
          <!--<span style="color: #1989fa" @click="seeSample">帮助<van-icon name="question-o" color="#1989fa" style="vertical-align: middle;"/></span>-->
          <!--<span :style="lookMapStyle" @click="lookMap">查看地图</span>-->
        <!--</div>-->

        <!-- 菜单 -->
        <van-grid :column-num="3" clickable :border="false" style="border-radius: .4rem;padding: .5rem;">
          <van-grid-item icon="question-o" text="帮助"  @click="seeSample"/>
          <van-grid-item icon="records" text="我要反馈" @click="toFeedback"/>
          <van-grid-item icon="location-o" text="查看地图" @click="lookMap"/>
        </van-grid>

      </div>

      <div class="contbox" style="padding: 30px 16px 20px 16px">
        <van-row class="rowstyle">
          <van-col span="12">
            <van-icon :name="startWork" size="50px"/>
          </van-col>
          <van-col span="12">
            <van-icon :name="endWork" size="50px"/>
          </van-col>
        </van-row>

        <van-row class="rowstyle">
          <van-col span="12" style="font-size: 1.2rem;">
            上班
          </van-col>
          <van-col span="12" style="font-size: 1.2rem;">
            下班
          </van-col>
        </van-row>

        <van-divider :style="{ backgroundColor: '#1989fa' }"/>

        <van-row class="rowstyle">
          <van-col span="12">
            {{startCard}}
          </van-col>
          <van-col span="12">
            {{endCard}}
          </van-col>
        </van-row>

        <van-row class="rowstyle" style="margin-top: 50px">
          <van-col span="12">
            <van-button size="small" type="info" v-bind:disabled="disableSubmit" style="padding: 0 2rem" @click="insertLeave(1)">上班打卡</van-button>
          </van-col>
          <van-col span="12">
            <van-button size="small" type="info" v-bind:disabled="disableSubmit" style="padding: 0 2rem" @click="insertLeave(2)">下班打卡</van-button>
          </van-col>
        </van-row>
      </div>

      <!--地图容器-->
      <div id="map"></div>

      <!--<div class="height10"></div>-->
      <baiduMap ref="baiduMapPop" :posPoint="posPoint" :checkPointList="checkPointList"></baiduMap>

    </div>

    <van-image-preview
      class="imagePreviewBox"
      v-model="showImage"
      :images="fujianImg"
      closeable
      :showIndex="false"
      @close="closeShowImage"
    >
    </van-image-preview>

  </div>
</template>

<script>
  Date.prototype.strftime = function (format) {
    var o = {
      "M+": this.getMonth() + 1,  //month
      "d+": this.getDate(),     //day
      "h+": this.getHours(),    //hour
      "m+": this.getMinutes(),  //minute
      "s+": this.getSeconds(), //second
      "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
      "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
      }
    }
    return format;
  }

  import Vue from 'vue';
  import BMap from 'BMap'
  import axios from 'axios'
  import request from '@/utils/request'
  import wx from "weixin-js-sdk";
  import cfg from '@/config/config';
  import mapSetApi from "@/api/mapSet";
  import baiduMap from "@/component/baiduMapView";

  // import assign from '@/utils/assign.js'

  import { Col, Row,Icon,Divider,Button, Cell,Grid, GridItem, CellGroup,Dialog   } from 'vant';
  import {ImagePreview} from "vant";
  Vue.use(Col);
  Vue.use(Row);
  Vue.use(ImagePreview);
  export default {
    name: "addLeave",
    // mixins: [assign],
    components: {
      [Row.name]: Row,
      [Dialog.name]: Dialog,
      [Col.name]: Col,
      [Icon.name]: Icon,
      [Divider.name]: Divider,
      [Button.name]: Button,
      [Cell.name]: Cell,
      [CellGroup.name]: CellGroup,
     [Grid.name]: Grid,
      [GridItem.name]: GridItem,
      baiduMap
    },
    inject: ['reload'],
    data() {
      return {
        showImage: false,
        fujianImg: [],
        startWork: require("@/assets/toWork.png"),
        endWork: require("@/assets/offWork.png"),
        disableSubmit: true, //定位失败的情况下是true不可点击，定位成功为false可以点击
        loadingPoint: 1,   //定位状态1 获取中，2 在打卡范围， 3 不在打卡范围 ，4 定位失败
        checkPointMsg: null,// 定位所属打卡点信息,提交用
        address: '正在获取...',
        address2: '正在获取...',
        startCard: "",   //上班打卡
        endCard: "",   //下班打卡
        nowtime: "--",
        timer: null,
        map: null,
        userNo: '',
        userserial:"",
        lookMapStyle:{
          color: "#1989fa"
        },
        // 打卡点列表
        checkPointList: [
          // {longitude: 121.51250578039334, latitude: 31.31992884580855, mc: "国霞路2号楼", cardRange: 100,bh:"1212414"},
          // {longitude: 121.51184103431596, latitude: 31.320059952996953, mc: "国霞路1号楼", cardRange: 100,bh:"1212415"},
          // {longitude: 121.4764323180635, latitude: 31.40825681780818, mc: "盘古路712弄小区", cardRange: 100,bh:"1212416"},
          // {longitude: 121.71144364992, latitude: 31.20039881004, mc: "上海市浦东新区川沙南市街42弄1号", cardRange: 100,bh:"1212417"},
          // {
          //   "bh": "9000005",
          //   "devSbId": "9000005",
          //   "mc": "大众办公楼2号门",
          //   "longitude": 121.193545,
          //   "latitude": 31.293712,
          //   "cardRange": "100"
          // },
          // {
          //   "bh": "9000004",
          //   "devSbId": "9000004",
          //   "mc": "大众办公楼1号门",
          //   "longitude": 121.195683,
          //   "latitude": 31.293835,
          //   "cardRange": "100"
          // },
          // {
          //   "bh": "9000003",
          //   "devSbId": "9000003",
          //   "mc": "大众办公楼1期",
          //   "longitude": 121.194874,
          //   "latitude": 31.293781,
          //   "cardRange": "100"
          // },
          // {
          //   "bh": "9000002",
          //   "devSbId": "9000002",
          //   "mc": "大众办公楼2期",
          //   "longitude": 121.196617,
          //   "latitude": 31.29375,
          //   "cardRange": "110"
          // },
          // {
          //   "bh": "9000001",
          //   "devSbId": "9000001",
          //   "mc": "步达考勤测试点",
          //   "longitude": 121.51252,
          //   "latitude": 31.319807,
          //   "cardRange": "50"
          // }
        ],
        posPoint: {
          longitude: 0,
          latitude: 0,
        },     //{longitude: 121.196617, latitude: 31.29375}
        RefreshNum: 1,
        timerd:null,
        times:0

      }
    },
    computed:{
      // checkPointList3: function () {
      //   let me = this ;
      //   let arr=[];
      //   for (let i = 0; i < me.checkPointList.length; i++) {
      //     let item = me.checkPointList[i];
      //     if (item.mc.indexOf("步达") == -1){
      //       arr.push(item)
      //     }
      //   }
      //   return arr
      // }
    },
    async mounted() {
      let me = this;
      // 实时时间
      this.timer = setInterval(function () {
        me.nowtime = me.UTCToLocalTimeString();
      }, 1000);

      if(this.$store.state.user && this.$store.state.user.USERNO){
        this.userNo = this.$store.state.user.USERNO;
        this.userserial = this.$store.state.user.USERSERIAL;
      } else {
        this.address2 = "获取失败";
        this.loadingPoint = 8;
        this.disableSubmit = true;
        this.$toast.fail("获取用户信息失败");
        this.lookMapStyle.color = "#999999";
        return
      }

      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "正在获取地理位置...",
      });

      this.timerd = setInterval(() => {
        this.times++;
        if (this.times > 15 && this.address2 == "正在获取...") {
          this.$toast.fail('获取定位异常，请重试');
          this.loadingPoint = 4;
          this.disableSubmit = true;
          this.address2 = "获取位置失败";
          this.lookMapStyle.color = "#999999";
        } else if (this.times > 11 && this.address2 != "正在获取..."){
          // clearInterval(this.timerd);
          this.times = 0;
          this.createMap2();
        }
      }, 1000);

      // 获取考勤点列表
      await this.getCalendarList();
        // 获取打卡状态
        this.getUserTtTaskCard();
      // 获取微信定位
      this.shareWechat();


    },
    destroyed(){
      clearInterval(this.timerd);
    },
    methods: {
      UTCToLocalTimeString() {
        var myDate = new Date();
        return myDate.strftime("yyyy-MM-dd hh:mm:ss");
      },

      // 获取企业微信签名并获取相应接口权限
      shareWechat() {
        let me = this;
        let url_temp = window.location.href.split("#")[0];
        // alert("获取签名的地址: " + url_temp);

          // axios.get(cfg.apiUrl + "wXLogin/getQySign?webUrl="+url_temp)
        request('get', cfg.apiUrl +'wXLogin/getQySign?webUrl='+url_temp).then(function(response) {
            console.log("签名请求结果：" + JSON.stringify(response.data));
          if(response.data){
            let data = response.data
            let appId = data.weixin.corpid;
            let nonceStr = data.weixin.nonceStr; // 必填，生成签名的随机串
            let timestamp = data.weixin.timestamp;  //生成签名的时间戳
            let signature = data.weixin.signature;  // 必填，签名，见附录1
            // alert(appId + "," + nonceStr + "," + timestamp + "," + signature);
            // 配置微信参数，并获取坐标
            wx.config({
              beta: true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              // appId: 'wx47bcab58ea28895f',     // 必填，公众号的唯一标识
              appId: appId, // 必填，企业微信的corpid，必须与当前登录的企业一致
              timestamp: timestamp, // 必填，生成签名的时间戳
              nonceStr:nonceStr, // 必填，生成签名的随机串
              signature: signature,// 必填，签名，见附录1
              // 必填，需要使用的JS接口列表，所有JS接口列表见官方js接口
              // 这里配置获取地理位置所需要的接口权限
              jsApiList: [
                'openLocation',
                'getLocation'
              ]
            });

            wx.ready(function(){
              // alert(location.href.split('#')[0]);
              // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
              wx.getLocation({
                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                  this.latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                  this.longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                  // var speed = res.speed; // 速度，以米/每秒计
                  var accuracy = res.accuracy; // 位置精度
                  // console.log('纬度：' + this.latitude + '经度：' + this.longitude + 'accuracy：' + accuracy);
                  // console.log("企业微信经度：" + res.longitude + "企业微信纬度：" + res.latitude);
                  // 使用企业微信内置地图查看位置接口
                  // wx.openLocation({
                  //   latitude: res.latitude, // 纬度，浮点数，范围为90 ~ -90
                  //   longitude: res.longitude, // 经度，浮点数，范围为180 ~ -180。
                  //   name: '', // 位置名
                  //   address: '', // 地址详情说明
                  //   scale: 1, // 地图缩放级别,整形值,范围从1~28。默认为16
                  // });
                  me.createMap(res.longitude, res.latitude);

                },
                fail: function(res) {
                  me.$toast.fail("获取定位失败");
                  me.loadingPoint = 4;
                  me.disableSubmit = true;
                  me.address2 = "获取位置失败";
                  // alert("定位失败："+ JSON.stringify(res));
                  console.log("fail" + JSON.stringify(res))
                },
                cancel: function (res) {
                  me.$toast.fail("用户拒绝授权获取地理位置");
                  me.loadingPoint = 4;
                  me.disableSubmit = true;
                  me.address2 = "获取位置失败";
                  console.log("cancel" + JSON.stringify(res))
                },
                complete: function (res) {
                  // console.log("complete" + JSON.stringify(res))
                },
              });

            });
            wx.error(function(res){
              me.$toast.fail("验证签名失败")
              me.loadingPoint = 5;
              me.disableSubmit = true;
              me.address2 = "获取失败";
              me.lookMapStyle.color = "#999999";
              // alert("验证签名失败："+ JSON.stringify(res));
              // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。

            });

          }
        }).catch(function(error) {
            me.$toast.fail("获取签名失败")
            me.loadingPoint = 6;
            me.disableSubmit = true;
            me.address2 = "获取失败";
            me.lookMapStyle.color = "#999999";
            // alert("获取签名失败："+ JSON.stringify(error));
        });
      },

      // 获取微信签名并获取相应接口权限
      Wechat() {
        let me = this;
        let url_temp = window.location.href.split("#")[0];
        axios.get(cfg.apiUrl + "wXLogin/getSign?webUrl="+url_temp).then(function(response) {
          // alert(JSON.stringify(response.data));
          if(response.data){
            let data = response.data
            let nonceStr = data["weixin"]["nonceStr"]  // 必填，生成签名的随机串
            let timestamp = data["weixin"]["timestamp"]  //生成签名的时间戳
            wx.config({
              beta: true,
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: data["weixin"]["appId"], // 必填，服务号
              timestamp: data["weixin"]["timestamp"], // 必填，生成签名的时间戳
              nonceStr: data["weixin"]["nonceStr"], // 必填，生成签名的随机串
              signature: data["weixin"]["signature"], // 必填，签名，见附录1
              jsApiList: ['hideMenuItems','hideAllNonBaseMenuItem']
            });
            wx.ready(function () {
              //隐藏所有按钮（“传播类”和“保护类"）
              wx.hideAllNonBaseMenuItem();
              wx.hideOptionMenu();
              //隐藏所有按钮（“传播类”和“保护类"）
              //以下隐藏部分按钮，分别为： 发送给朋友，分享到朋友圈，分享到QQ，分享到Weibo，收藏，分享到FB，分享到 QQ 空间，复制链接，阅读模式
              // wx.hideMenuItems({
              // menuList: ['menuItem:share:appMessage','menuItem:share:timeline','menuItem:share:qq','menuItem:share:weiboApp','menuItem:favorite','menuItem:share:facebook','menuItem:share:QZone','menuItem:copyUrl','menuItem:readMode'] // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
              // });
              // 获取位置
              wx.getLocation({
                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                  this.latitude = res.latitude // 纬度，浮点数，范围为90 ~ -90
                  this.longitude = res.longitude // 经度，浮点数，范围为180 ~ -180。
                  // var speed = res.speed // 速度，以米/每秒计
                  var accuracy = res.accuracy // 位置精度
                  // console.log('纬度：' + this.latitude + '经度：' + this.longitude + 'accuracy：' + accuracy)
                  // alert("微信经度：" + res.longitude + "微信纬度：" + res.latitude);
                  me.createMap(res.longitude, res.latitude);
                },
                fail: function(res) {
                  me.$toast.fail("获取定位失败")
                  // console.log(JSON.stringify(res))
                },
                cancel: function (res) {
                  me.$toast.fail("用户拒绝授权")
                },
              })
            });
            wx.error(function(res){
              // alert("验证签名失败: " + JSON.stringify(res));
              me.$toast.fail("验证签名失败")
              me.loadingPoint = 5;
              me.disableSubmit = true;
              me.address2 = "获取失败";
              me.lookMapStyle.color = "#999999";
              // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。

            });

          }
        })
          .catch(function(error) {
            me.$toast.fail("获取签名失败")
            // alert(error);
            // console.log(error);
          });
      },

      async createMap(lng, lat) {
        var that = this;
        that.loadingPoint = 1;
        that.disableSubmit = true;
        // 创建Map实例
        var map = new BMap.Map('map');
        that.map = map;
        // 初始化地图,设置中心点坐标和地图级别
        // map.centerAndZoom(new BMap.Point(121.49897906003335, 31.252858810301676), 18)
        // map.centerAndZoom("上海", 18);
        //添加地图类型控件
        // map.addControl(new BMap.MapTypeControl({
        //   mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP]
        // }))

        var geoc = new BMap.Geocoder();

        // try {
        //   let res = await this.$jsonp("http://api.map.baidu.com/geoconv/v1/",{
        //     from: 1,
        //     to: 5,
        //     ak: 'htgznmBQ0fTOjLFTz98yrUb5IiABdXOG',
        //     coords: lng+","+ lat
        //   });
        //   console.log("转换后的坐标："+JSON.stringify(res));
        //   if (res.status == 0){
        //     that.posPoint = {longitude: res.result.x, latitude: res.result.y};
        //     geoc.getLocation(that.posPoint, function (rs) {
        //       // console.log('1111')
        //       console.log("444ddd"+JSON.stringify(rs))
        //       var addComp = rs.addressComponents;
        //       that.address2 = rs.surroundingPois[0].title;
        //       that.$toast.clear();
        //     });
        //     // 坐标范围判断
        //     that.comparePoint(map, res.result.x, res.result.y);
        //   } else{
        //     this.$toast.fail("转换坐标失败！")
        //     console.log("转换坐标失败！")
        //   }
        // }catch (ex){
        //   this.$toast.fail("网络请求失败！")
        //   console.log("网络请求失败！")
        // }


        var translateCallback = function (data) {
          // console.log("转换后： " + JSON.stringify(data));
          if (data.status === 0) {
            // var marker = new BMap.Marker(data.points[0]);
            // map.addOverlay(marker);
            // map.panTo(data.points[0]);
            // var label = new BMap.Label("转换后的百度坐标（正确）", {offset: new BMap.Size(20, -10)});
            // marker.setLabel(label); //添加百度label
            // map.setCenter(data.points[0]);
            that.posPoint = {longitude: data.points[0].lng, latitude: data.points[0].lat};
          console.log(that.posPoint);
            geoc.getLocation(data.points[0], function (rs) {
              // console.log('1111')
              console.log("转换后获取到附近点列表："+JSON.stringify(rs))
              var addComp = rs.addressComponents;
              // mk.setPosition(r.point)
              // mk.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
              // alert("地点信息：" + JSON.stringify(addComp));
              // that.address = addComp.city + addComp.district + addComp.street + addComp.streetNumber;
              // 取address得地址详细但很多时候不精准，所以address2是取附近列表中的第一个
              that.address2 = rs.surroundingPois[0].title;
              if (that.address2.indexOf("上海大众") > -1){
                that.address2 = that.address2.length < 4?"上汽大众":  "上汽大众"+ that.address2.slice(4,that.address2.length -1);
              }
              console.log(that.address2 );
              that.$toast.clear();
            });
            // 坐标范围判断
            that.comparePoint(map, data.points[0].lng, data.points[0].lat);
          } else{
            that.$toast.fail("获取位置异常！")
          }
        }

        console.log("转换开始：" + "微信经度："+lng +  "," + "微信纬度："+lat);
        try {
          if (that.checkPointList.length != 0){
            let centerPointer = new BMap.Point(lng, lat);
            // console.log(centerPointer)
            let convertor = new BMap.Convertor();
            let pointArr = [];
            pointArr.push(centerPointer);
            convertor.translate(pointArr, 1, 5, translateCallback)
          } else {
            that.loadingPoint = 9;
          }

        } catch (e) {
          that.$toast.fail(e)
        }

      },

      // 持续定位
       createMap2() {
        var that = this;
        // 获取位置
        // console.log("持续定位2：" +  wx.getLocation)
        wx.getLocation({
          type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
          success: function (res) {
            this.latitude = res.latitude // 纬度，浮点数，范围为90 ~ -90
            this.longitude = res.longitude // 经度，浮点数，范围为180 ~ -180。
            // var speed = res.speed // 速度，以米/每秒计
            var accuracy = res.accuracy // 位置精度
            // console.log('纬度：' + this.latitude + '经度：' + this.longitude );
            console.log("持续微信经度：" + res.longitude + "持续微信纬度：" + res.latitude);
            // me.createMap(res.longitude, res.latitude);

            var geoc = new BMap.Geocoder();
            var translateCallback = function (data) {
              console.log("持续回调：" + JSON.stringify(data));
              if (data.status === 0) {
                that.posPoint = {longitude: data.points[0].lng, latitude: data.points[0].lat};
                console.log(that.posPoint);
                geoc.getLocation(data.points[0], function (rs) {
                  console.log("持续rs3：" + JSON.stringify(rs));
                  var addComp = rs.addressComponents;
                  that.address2 = rs.surroundingPois[0].title;
                  if (that.address2.indexOf("上海大众") > -1){
                    that.address2 = that.address2.length < 4?"上汽大众":  "上汽大众"+ that.address2.slice(4,that.address2.length -1);
                  }
                  console.log(that.address2);
                  that.$toast.clear();
                });
                // 坐标范围判断
                that.comparePoint(that.map, data.points[0].lng, data.points[0].lat);
              } else{
                that.$toast.fail("获取位置异常！")
              }
            }
            // console.log("转换开始：" + "微信经度："+lng +  "," + "微信纬度："+lat);
            try {
              if (that.checkPointList.length != 0){
                let centerPointer = new BMap.Point(res.longitude, res.latitude);
                // console.log(centerPointer)
                let convertor = new BMap.Convertor();
                let pointArr = [];
                pointArr.push(centerPointer);
                convertor.translate(pointArr, 1, 5, translateCallback)
              }else {
                that.loadingPoint = 9;
              }
            } catch (e) {
              that.$toast.fail()
            }
          },
          fail: function(res) {
            that.$toast.fail("获取定位失败");
            that.loadingPoint = 4;
            that.disableSubmit = true;
            that.address2 = "获取位置失败";
            // console.log(JSON.stringify(res))
          },

        })


      },

      // 坐标比对
      comparePoint(map, pointX, pointY) {
        console.log("坐标对比");
        let that = this;
        // 判断，如果匹配设置好的打卡点范围，就返回2，不匹配就返回3
        let len = that.checkPointList.length;
        let arr = [];
        for (let i = 0; i < len; i++) {
          let item = that.checkPointList[i];
          let centerPoint = new BMap.Point(item.longitude, item.latitude);   //中心点  121.51250578039334,lat: 31.31992884580855
          let positionPoint = new BMap.Point(pointX, pointY);   //定位点
          let distance = map.getDistance(centerPoint, positionPoint);
          console.log("距离为：" + distance);
          if (parseInt(distance) < item.cardRange) {
            arr.push(item);
          }
        }
        console.log("在距离范围内的考勤点：" + JSON.stringify(arr));
        if (arr.length > 0) {
          that.checkPointMsg = arr[0];
          that.disableSubmit = false;
          that.loadingPoint = 2;
          that.lookMapStyle.color = "#1989fa";
          that.$toast.clear();
          // alert("当前打卡点为：" + that.checkPointMsg.mc)
        } else {
          that.checkPointMsg = null;
          that.disableSubmit = true;
          that.loadingPoint = 3;
          that.lookMapStyle.color = "#1989fa";
          that.$toast.clear();
          // that.$toast.fail("不在打卡范围内")
        }

      },

      // 获取考勤点列表
       async getCalendarList() {
         let param = {
           pageNumber: 1,
           pageSize: 2000,
           serchTxt: "",
           pkSysUser: this.userserial,
         };
         try {
           let res = await mapSetApi.getDzStDeviceList(param);
           if (res.data.success) {
             this.checkPointList = res.data.result.records;
             console.log(this.checkPointList)
             if (this.checkPointList.length == 0) {
               this.loadingPoint = 9;
               this.disableSubmit = true;
               this.address2 = "您当前尚未开通任何移动考勤点";
               this.lookMapStyle.color = "#999999";
               this.$toast.clear();
               clearInterval(this.timerd);
               Dialog.alert({
                 message: '您当前尚未开通任何移动考勤点，如有需要，请通过您所在部门申请开通，谢谢',
               }).then(() => {
                 // on close
               });

             }
           } else {
             clearInterval(this.timerd);
             this.loadingPoint = 7;
             this.disableSubmit = true;
             this.address2 = "获取考勤点失败";
             this.$toast.fail(res.data.message);
             this.lookMapStyle.color = "#1989fa";
           }
         } catch (e) {
           clearInterval(this.timerd);
           this.loadingPoint = 7;
           this.disableSubmit = true;
           this.address2 = "获取考勤点失败";
           this.$toast.fail("获取考勤点失败");
           this.lookMapStyle.color = "#1989fa";
         }

       },
      //打卡提交
      async insertLeave(num) {
        // alert(this.checkPointMsg.devSbId);
        this.disableSubmit = true;

        let param = {
          mjDevid: this.checkPointMsg.devSbId,    //this.checkPointMsg.devSbId   国霞路259（9010296）
          jlogDir: num ,    // num: 1 签到打卡啊，2 签退打卡
          jlogUserId: this.userNo
        };
        // alert("mjDevid: " + this.checkPointMsg.devSbId + ", " +  "jlogDir: " + num);
        this.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true,
          message: "正在提交...",
        });
        try {
          let res = await mapSetApi.saveJuserKqRecord(param);
          this.$toast.clear();
          // console.log(res);
          if (res.data.success) {
            this.$toast.success('提交成功！');
            this.getUserTtTaskCard();
          } else {
            this.$toast.fail(res.data.message)
          }
          setTimeout(()=>{
            this.disableSubmit = false;
          },3000)
        } catch (e) {
          this.$toast.fail(e)
        }


      },
      // 获取打卡状态
      async getUserTtTaskCard(){
        // alert( this.$store.state.weChatId);
        // alert( this.$store.state.user.USERNO);

        let res = await mapSetApi.getUserTtTaskCard({
          jlogUserId: this.userNo,
        });
        // console.log(res);
        // alert(JSON.stringify(res.data));
        if (res.data.success) {
          let newData = res.data.result;
          let startCut = newData.filter(el=>{return el.JLOGDIR == 1})[0];  // jlogDir: 1 签到打卡
          let endCut = newData.filter(el=>{return el.JLOGDIR == 2})[0];  // jlogDir: 1 签到打卡
          // alert("签到：" + startCut.CUT + "," + "签退：" + endCut.CUT);

          if (startCut.CUT == 0){
            this.startCard = "";
          } else if (startCut.CUT > 0){
            this.startCard = "已打卡";
          }

          if (endCut.CUT == 0){
            this.endCard = "";
          } else if (endCut.CUT > 0){
            this.endCard = "已打卡";
          }
        } else {
          this.$toast.fail(res.data.message)
        }
      },

      goBack() {
        this.$toast.clear();
        this.$router.go(-1);
      },

      toFeedback(){
        this.posPoint.address = this.address2;
        this.$router.push({path:"/feedback",query: this.posPoint });
      },

      Refresh(){
        this.reload()  //苹果手机无效
      },
      Refresh2(){
        this.RefreshNum++;
        setTimeout(()=>{
          this.RefreshNum == 1;
        },3000)
        location. reload();
      },
      Refresh3(){
        this.$router.go(0)  //都可以用
      },
      lookMap(){
        // this.$refs.baiduMapPop.open();
        console.log(this.loadingPoint);
        if (this.loadingPoint != 4 && this.loadingPoint != 5 && this.loadingPoint != 6 && this.loadingPoint != 1 && this.loadingPoint != 7 && this.loadingPoint != 8 && this.loadingPoint != 9 && this.posPoint != null){
          this.$refs.baiduMapPop.open();
        }
      },
      seeSample() {
        this.fujianImg.push(require('@/assets/helpImg.jpg'));
        this.showImage = true
      },
      closeShowImage() {
        this.fujianImg = [];
        this.showImage = false
      },

    },
  }
</script>

<style>

  .rowstyle {
    text-align: center;
    margin: 16px 0;
  }

  .littletip {
    background-color: #fff;
    border-radius: .4rem;
    display: inline-block;
    padding: .2rem .5rem;
  }
  .littletip p{
    margin: 0;
    font-size: 1.2rem;
  }

</style>
